/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import java.io.Serializable;
import java.lang.reflect.Array;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.servlet.http.HttpServletRequest;
import jpa.entities.Produto;
import jpa.session.ProdutoFacade;
import jsf.ProdutoController;
import jsf.util.JsfUtil;

/**
 *
 * @author carlos
 */
@ManagedBean(name = "forwardBean")
@SessionScoped
@Stateless
public class ForwardBean implements Serializable {

    private String action;

    public String getAction() {
        return action;
    }

    public String getActionParam() {
        return actionParam;
    }
    private String actionParam;

    public void navigate(PhaseEvent event) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String outcome = queryString("action").toString(); // Do your thing?
        UserManager login = (UserManager) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userManager");

        try {
            if (outcome.equals("produtoView")) {
                ProdutoController prod = new ProdutoController();
                prod.setSelected(Integer.parseInt(queryString("actionParam").toString()));
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("produtoController", prod);
            }
            if (outcome.equals("facebook")) {
                String produtos[] = queryString("actionParam").toString().split(",");
                //String produtos[] = "59".split(",");
                BuyManager compra = new BuyManager();
                ProdutoFacade prod = new ProdutoFacade();



                for (int i = 0; i < produtos.length; i++) {
                    compra.AdicionarPedido(prod.find(Integer.parseInt(produtos[i])));
                }

                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("buyManager", compra);
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("itemPedido", compra.getList());

                if (login.isAuthenticated()) {
                    outcome = "carrinho";
                }
            }

            facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, null, outcome);

        } catch (Exception e) {
            JsfUtil.addErrorMessage("Erro no redirecionamento");
        }
    }

    public static Object queryString(String key) {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

        return request.getParameter(key);

    }
    // Add/generate the usual boilerplate.
}
